package com.ypf.rpc.factory;


import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 提供服务的工厂 提供具体的调用对象
 */

@Slf4j
public class ServiceFactory {

    // 保存所有 有注解的@RpcService的集合
    public static final Map<String,Object> serviceFactory = new ConcurrentHashMap<>();

    // 添加已注解的类进工厂
    public <T> void  addServiceProvider(T service,String serviceName){
        if (serviceFactory.containsKey(serviceName)){
            return;
        }
        serviceFactory.put(serviceName,service);  // 就一行代码 本身ConcurrentHashMap就是线程安全的
        log.debug("服务类{}添加进serviceFactory",serviceName);
    }

    // 远程调用接口从该方法获取
    public Object getServiceProvider(String serviceName){
        Object service = serviceFactory.get(serviceName);
        if (service==null){
            throw new RuntimeException("未发现该服务");
        }

        return service;
    }
}
